package com.jushu.storbox.database;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;

import com.jushu.storbox.entities.AlbumFolderInfo;

public class AlbumFolderDao extends BaseDao implements IAlbumFolderDao {

	public long insertAlbumFolder(AlbumFolderInfo albumFolder) {
		long res = -1;
		AlbumFolderInfo tempAlbumFolder = getAlbumFolder(
				albumFolder.getOwnerBy(), albumFolder.getFolderPath());
		if (tempAlbumFolder == null) {
			res = getDb().insert(IAlbumFolderDao.TABLE_NAME, null,
					albumFolder.toContentValues());
		}
		return res;
	}

	public AlbumFolderInfo getAlbumFolder(String ownerId, String folderPath) {
		AlbumFolderInfo albumFolder = null;
		StringBuilder sql = new StringBuilder();
		sql.append("select * from ").append(IAlbumFolderDao.TABLE_NAME);
		sql.append(" where ");
		sql.append(IAlbumFolderDao.OWNER_ID).append("=?");
		sql.append(" and ");
		sql.append(IAlbumFolderDao.FOLDER_PATH).append("=?");

		Cursor cursor = getDb().rawQuery(sql.toString(),
				new String[] { ownerId, folderPath });
		if (cursor != null) {
			if (cursor.getCount() > 0 && cursor.moveToFirst()) {
				albumFolder = new AlbumFolderInfo();
				albumFolder.fromCursor(cursor);
			}
			cursor.close();
		}
		return albumFolder;
	}

	public List<AlbumFolderInfo> getAlbumFolders(String ownerId) {
		List<AlbumFolderInfo> albumList = new ArrayList<AlbumFolderInfo>();
		StringBuilder sql = new StringBuilder();
		sql.append("select * from ").append(IAlbumFolderDao.TABLE_NAME);
		sql.append(" where ");
		sql.append(IAlbumFolderDao.OWNER_ID).append("=?");

		Cursor cursor = getDb().rawQuery(sql.toString(),
				new String[] { ownerId });
		if (cursor != null) {
			while (cursor.moveToNext()) {
				AlbumFolderInfo albumFolder = new AlbumFolderInfo();
				albumFolder.fromCursor(cursor);
				albumList.add(albumFolder);
			}
			cursor.close();
		}
		return albumList;
	}

	public void deleteAlumbFolderInfo(AlbumFolderInfo albumFolder) {
		String whereCase = IAlbumFolderDao.OWNER_ID + "=? and "
				+ IAlbumFolderDao.FOLDER_PATH + "=?";
		getDb().delete(
				IAlbumFolderDao.TABLE_NAME,
				whereCase,
				new String[] { albumFolder.getOwnerBy(),
						albumFolder.getFolderPath() });
	}

	public int updateAlumbFolderInfo(AlbumFolderInfo albumFolder) {
		String whereCase = IAlbumFolderDao.OWNER_ID + "=? and "
				+ IAlbumFolderDao.FOLDER_PATH + "=?";
		return getDb().update(
				IAlbumFolderDao.TABLE_NAME,
				albumFolder.getAlbumFolderCV(),
				whereCase,
				new String[] { albumFolder.getOwnerBy(),
						albumFolder.getFolderPath() });
	}

	public int clearByUserId(String ownerId) {
		String whereCase = IAlbumFolderDao.OWNER_ID + "=?";
		return getDb().delete(IAlbumFolderDao.TABLE_NAME, whereCase,
				new String[] { ownerId });
	}

	@Override
	public long getLastUpdateTime(String objectId) {
		return 0;
	}

	@Override
	public void updateLastUpdateTime(String objectId) {
	}

}
